/*
 * gsensor.c
 *
 *  Created on: 16.05.2011
 *      Author: OrGeJs
 */

#include <avr/io.h>
#include <avr/delay.h>

#include "gsensor.h"

#define G_CONST fixedpoint_fromFloat(9.81)	/*acceleration of gravity*/

bool bGetAccelaration(fixedpoint_t *pwAcceleration) {

	fixedpoint_t wGValue;

	ADMUX &= ~(1 << MUX0); /*choose ADCO*/

	/*Special care should be taken when changing differential channels. Once a differential channel
	 has been selected, the gain stage may take as much as 125 us to stabilize to the new value.
	 Thus conversions should not be started within the first 125 us after selecting a new differential
	 channel. Alternatively, conversion results obtained within this period should be discarded.*/

	_delay_us(125);

	ADCSR |= (1 << ADSC); /*start conversion*/

	do {

	} while (!(ADCSR & (1 << ADIF))); /*wait until end of conversion*/

	wGValue = (fixedpoint_t) ADCW; /*read register and calculate g*/
	/*ADCW * (4.0 / 1024.0) already done by converting to fixedpoint_t*/
	wGValue -= fixedpoint_fromFloat(2.0); /*move to zero*/
	*pwAcceleration = fixedpoint_mul(wGValue, G_CONST); /*calculate acceleration*/

	return true;
}
